package com.xk.meeting.controller;

import com.xk.meeting.entity.Apply;
import com.xk.meeting.entity.Meeting;
import com.xk.meeting.entity.User;
import com.xk.meeting.service.ApplyService;
import com.xk.meeting.service.ApplyServiceImpl;
import com.xk.meeting.service.MeetingService;
import com.xk.meeting.service.MeetingServiceImpl;
import com.xk.meeting.utils.MyDateConverter;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@WebServlet("/addApply")
public class AddApplyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> applyMap = request.getParameterMap();
        Apply apply = new Apply();
        try {
            ConvertUtils.register(new MyDateConverter(), Date.class);
            BeanUtils.populate(apply,applyMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        User user = (User)request.getSession().getAttribute("user");
        if (user != null){
            apply.setUid(user.getId());
            ApplyService applyService = new ApplyServiceImpl();
            int count = applyService.addApply(apply);
            if (count > 0){
                request.setAttribute("msg","已发送申请,等待审核通过");
                request.getRequestDispatcher("apply.jsp").forward(request,response);
            }else {
                response.sendRedirect("errorPage.jsp");
            }
        }else {
            response.sendRedirect("login.jsp");
        }
    }
}
